package cj.utils.sc;

import java.util.Arrays;
import net.sf.json.JSONObject;
import org.apache.http.protocol.HTTP;
import cj.utils.HttpClientUtil;
import cj.utils.MD5Security;

/**
 *  消费接口已经做完，接口格式为：
 *  http://tapi.dachuw.net/nfcBACJRB2/consumeBAAccount?print_no=8150211033&amp;card_pwd=1A0A1FDAAD01296D&consume_amount=1&partner=5208&sign=EF12756387F74EB6B6D15D8058E4AB71
 *  该接口为测试接口，测试的卡号和密码分别为：8150211033，222222
 *  传递参数：
 *  partner：接入方ID（优讯通编制接入方-长报为5208）
 *  print_no：印刻卡号
 *  card_pwd：密码16位MD5加密，超过部分后台自动截取，请严格按照16位MD5加密
 *  consume_amount：消费金额
 *  sign：以上参数进行按照key=value的方式按照ASCLL码从小到大进行排序，并用&进行连接后拼接signkey=SIGN_KEY进行MD5加密后得到sign
 *  具体加密算法譬如：a:xxx，c:yyy，b:uuu
 *  1、key=value按照ASCLL码排序：String = a=xxx&b=uuu&c=yyy
 *  2、拼接signkey：String = String&signkey=SIGN_KEY
 *  3、对上述String进行MD5签名：MD5（String）
 *  返回参数为：
 *  消费成功：
 *  {"resp_code":0,"resp_msg":"recharge consume is ok.","resp_detail":{"print_no":"8150211033","card_no":"8027110115021103","consume_amount":"1","sign":"6C04EF5A4DF06F517E4131AB942D818D"}}
 *  开户失败：
 *  {"resp_code":"3","resp_msg":"sign is wrong.","resp_detail":""}
 *  1、返回码说明：0-消费成功，其他-消费失败，失败原因在resp_detail字段中，为Unicode编码，可以直接查看。
 *  2、接口返回一律采用JSON返回。
 *  3、返回字段：print_no：印刻号，card_no：卡片内置逻辑号，consume_amount：初始化金额，sign：优讯通加密校验值
 * @author Administrator
 *
 */
public class ZWHSignKeyUtil {
	
	//接入方ID
	public static final String partner="partner=5208";
	
	//长报的SIGN_KEY为：33183d625ca0cb7c5d50ff0598a1a66b
	public static final String signkey = "33183d625ca0cb7c5d50ff0598a1a66b";
	
	public static void main(String[] args) throws Exception
	{
		String print_no = "8150211033";
		String card_pwd = "222222";
		String consume_amount = "1";
		submitToTapi(print_no, card_pwd, consume_amount);
	}
	
	/**
	 * 提交武汉通支付
	 * @param print_no	印刻卡号
	 * @param card_pwd	密码
	 * @param consume_amount	消费金额
	 * @return
	 * @throws Exception 
	 */
	public static JSONObject submitToTapi(String print_no,String card_pwd,String consume_amount) throws Exception
	{
		
		String pwd = MD5Security.code(card_pwd, 16);
		print_no="print_no="+print_no;
		card_pwd="card_pwd="+pwd;
		consume_amount="consume_amount="+consume_amount;
		
		String sign="sign=";
		String[] arr = new String[] { print_no, card_pwd, consume_amount,partner};
		// 将token、timestamp、nonce三个参数进行字典排序
		Arrays.sort(arr);
		StringBuilder content = new StringBuilder();
		for (int i = 0; i < arr.length; i++) {
			content.append(arr[i]+"&");
		}
		//讲参数加上signkey并加密
		String ss = content+"signkey="+signkey;
		sign += MD5Security.md5(ss);
		//请求远端服务
		return invokeTapi(content+sign);
	}
	
	/**
	 * 请求远端服务
	 * @param sign
	 */
	private static JSONObject invokeTapi(String sign)
	{
		String url="http://tapi.dachuw.net/nfcBACJRB2/consumeBAAccount?"+sign;
		
		String bodyJson = HttpClientUtil.get(url, HTTP.UTF_8);
		
		JSONObject jsobj =new JSONObject().fromObject(bodyJson);
		return jsobj;
	}
}
